import Vue from "vue";
import Vuex from "vuex";
import { reqGetUsersList, reqGetAllUsers } from "../api/users";

Vue.use(Vuex);

const state = {
  users: [], // 用户分页数据
  total: 0, // 用户总数
};

const getters = {};

const actions = {
  async getUsersList({ commit }, { page, limit }) {
    // 发送请求
    // const { data: users } = await reqGetUsersList(page, limit);
    // const {
    //   data: { length: total },
    // } = await reqGetAllUsers();
    // const response = await reqGetAllUsers();
    // const data = response.data;
    // const length = data.length;
    // const total = length;

    // const promise1 = reqGetUsersList(page, limit);
    // const promise2 = reqGetAllUsers();
    // Promise.all([promise1, promise2]);
    const result = await Promise.all([
      reqGetUsersList(page, limit),
      reqGetAllUsers(),
    ]);

    // console.log(result, commit);
    // 触发mutation函数
    commit("GET_USERS_LIST", result);
  },
};

const mutations = {
  GET_USERS_LIST(state, result) {
    state.users = result[0].data;
    state.total = result[1].data.length;
  },
};

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
});
